<template>
  <div class="container">
    <div class="login-box" >
      <!-- 登录方式切换选项卡 -->
      <div v-show="!roleDialogVisible">
        <div class="login-tabs">
          <button :class="{ active: currentTab === 'account' }" @click="currentTab = 'account'">
            账号登录
          </button>
          <button :class="{ active: currentTab === 'phone' }" @click="currentTab = 'phone'">
            手机登录
          </button>
        </div>
        <!-- 登录组件容器 -->
        <div class="login-content">
          <account v-if="currentTab === 'account'" @login-success="handleLoginSuccess" ref="accountComponent" />
          <phone v-else @login-success="handleLoginSuccess" ref="phoneComponent" />
        </div>
      </div>

      <!-- 角色选择对话框 -->
      <el-dialog title="选择角色" :visible.sync="roleDialogVisible" width="400px" :before-close="handleRoleDialogClose"
        :modal="true" :close-on-click-modal="false" @keydown.enter.native="confirmRoleSelection">
        <div v-if="multiRoleData">
          <p>请选择要使用的角色：</p>
          <el-radio-group v-model="selectedRoleId">
            <el-radio v-for="role in multiRoleData.roles" :key="role.roleId" :label="role.roleId"
              style="display: block; margin: 10px 0;">
              {{ role.roleName }}
              <span v-if="role.isAdmin === 1" style="color: #67C23A;">(管理员)</span>
              <span v-if="role.isCollector === 1" style="color: #409EFF;">(采集员)</span>
            </el-radio>
          </el-radio-group>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleCancelRoleSelection">取消</el-button>
          <el-button type="primary" @click="confirmRoleSelection" :loading="roleSelectLoading">确认</el-button>
        </span>
      </el-dialog>


    </div>
  </div>
</template>

<script>
import Account from './components/account.vue'
import Phone from './components/phone.vue'
import { selectRole } from '@/api/user'
import { setToken } from '@/utils/auth'
import { setUser } from '@/utils/storage'

export default {
  name: "Login",
  components: {
    Account,
    Phone,
  },
  data() {
    return {
      currentTab: 'account',
      roleDialogVisible: false,
      selectedRoleId: null,
      multiRoleData: null,
      roleSelectLoading: false,
      tempToken: ''
    }
  },
  methods: {
    handleLoginSuccess(response) {
      console.log('登录响应:', response) // 调试信息

      // 检查是否需要角色选择
      if (response && response.result && response.result.needRoleSelection) {
        this.multiRoleData = response.result
        this.tempToken = response.result.tempToken
        this.selectedRoleId = response.result.roles[0]?.roleId || null
        this.roleDialogVisible = true
      } else if (response && response.result) {
        // 单角色用户直接跳转
        this.$router.push({ path: '/' })
      } else {
        console.error('无效的响应格式:', response)
        this.$message.error('登录响应格式错误')
      }
    },

    async confirmRoleSelection() {
      if (!this.selectedRoleId) {
        this.$message.warning('请选择一个角色')
        return
      }

      this.roleSelectLoading = true
      try {
        const response = await selectRole(this.multiRoleData.userId, this.selectedRoleId)
        console.log('角色选择响应:', response)

        if (response.code === 200) {
          const data = response.result
          console.log('角色选择成功数据:', data)

          // 1. 先更新store中的token状态
          this.$store.commit('user/SET_TOKEN', data.token)
          this.$store.commit('user/SET_USERID', data.userId)

          // 2. 持久化到 Cookie 与 localStorage，确保路由守卫能识别已登录状态
          setToken(data.token)
          setUser(data.username, data.userId)
          const user = {
            username: data.username,
            userId: data.userId
          }
          console.log('indexuser', user)
          localStorage.setItem('user', JSON.stringify(user))
          localStorage.setItem('token', data.token)
          localStorage.setItem('userId', data.userId.toString())

          // 3. 等待store状态更新完成
          await this.$nextTick()

          // 4. 调试：检查store中的token
          console.log('Store中的token:', this.$store.state.user.token)
          console.log('LocalStorage中的token:', localStorage.getItem('token'))

          // 5. 获取用户权限信息
          try {
            await this.$store.dispatch('user/getInfo')
            this.$message.success('登录成功')
            this.roleDialogVisible = false
            this.$router.push({ path: '/' })
          } catch (error) {
            console.error('获取权限信息失败:', error)
            // 即使权限获取失败，也允许登录
            this.$message.warning('登录成功，但权限加载失败')
            this.roleDialogVisible = false
            this.$router.push({ path: '/' })
          }
        } else {
          this.$message.error(response.message || '角色选择失败')
        }
      } catch (error) {
        console.error('完整的角色选择错误:', error)

        if (error.response) {
          console.error('错误响应状态:', error.response.status)
          console.error('错误响应数据:', error.response.data)

          if (error.response.status === 401) {
            this.$message.error('认证失败，token无效')
            // 清除所有存储的token
            this.$store.dispatch('user/resetToken')
            localStorage.removeItem('token')
            localStorage.removeItem('userId')
            this.roleDialogVisible = false
          }
        } else {
          this.$message.error('网络错误: ' + (error.message || '未知错误'))
        }
      } finally {
        this.roleSelectLoading = false
      }
    },

    handleRoleDialogClose(done) {
      // 关闭对话框时清空数据
      this.multiRoleData = null
      this.selectedRoleId = null
      this.tempToken = ''
      done()
    },
    handleCancelRoleSelection() {
      // 取消角色选择时清空用户名和密码
      this.roleDialogVisible = false;

      // 如果当前是账号登录页面，则调用其清空表单的方法
      if (this.currentTab === 'account' && this.$refs.accountComponent) {
        this.$refs.accountComponent.clearLoginForm();
      }
      if (this.currentTab === 'phone' && this.$refs.phoneComponent) {
        this.$refs.phoneComponent.clearLoginForm();
      }
      // 清空角色选择相关数据
      this.multiRoleData = null;
      this.selectedRoleId = null;
      this.tempToken = '';
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  width: 100%;
  background: url("~@/assets/login.png") no-repeat center center fixed;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;

  .login-box {
    background: rgba(255, 255, 255, 0.95);
    padding: 2rem;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    width: 400px;
    max-width: 90%;

    .login-tabs {
      display: flex;
      margin-bottom: 1.5rem;
      border-radius: 8px;
      overflow: hidden;
      background: #f5f5f5;

      button {
        flex: 1;
        padding: 12px 20px;
        border: none;
        background: transparent;
        cursor: pointer;
        font-size: 16px;
        color: #666;
        transition: all 0.3s ease;

        &.active {
          background: #fff;
          color: #2d8cf0;
          font-weight: 500;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        &:hover:not(.active) {
          background: rgba(255, 255, 255, 0.7);
        }
      }
    }

    .login-content {
      min-height: 300px; // 保持切换时高度一致
    }
  }
}

::v-deep .el-dialog__body {
  p {
    margin-bottom: 15px;
    color: #606266;
  }

  .el-radio {
    padding: 8px 0;

    &:hover {
      background-color: #f5f7fa;
      border-radius: 4px;
    }
  }
}
</style>
